package com.andong.service.impl;

import com.andong.domain.entity.Student;
import com.andong.domain.pojo.Result;
import com.andong.mapper.StudentMapper;
import com.andong.service.StudentService;
import com.andong.utils.AliSMSUtils;
import com.andong.utils.CommonUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andong.domain.entity.RealScore;
import com.andong.service.RealScoreService;
import com.andong.mapper.RealScoreMapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.andong.utils.SystemConstant.*;

/**
 * @author 王海云
 * @description 针对表【real_score(学员真实成绩表)】的数据库操作Service实现
 * @createDate 2024-02-27 11:40:29
 */
@Service
public class RealScoreServiceImpl extends ServiceImpl<RealScoreMapper, RealScore> implements RealScoreService {
    @Resource
    private StudentService studentService;
    @Resource
    private AliSMSUtils aliSMSUtils;

    @Override
    public Result getScoreById(Long id) {
        List<RealScore> list = lambdaQuery().
                eq(RealScore::getStudentId, id).
                orderByAsc(RealScore::getSubject)
                .orderByAsc(RealScore::getTimes).list();
        return Result.success(list);
    }

    @Override
    public Result saveScore(RealScore realScore) {
        Long studentId = realScore.getStudentId();
        // 查询学生信息
        Student student = Db.lambdaQuery(Student.class).eq(Student::getId, studentId).one();
        // 判断此次成绩是否要删除账号
        if (CommonUtils.isDelete(realScore.getScore(), realScore.getTimes(), realScore.getSubject(), student.getLicenseType())) {
            studentService.removeById(studentId);
            // 短信通知学员
            try {
                aliSMSUtils.sendLogout(student.getPhone(),
                        student.getName(),
                        realScore.getSubject() == SUBJECT_THREE_NUMBER ? SUBJECT_THREE : SUBJECT_TWO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 判断是否进入下一阶段
        if (CommonUtils.isNextStage(realScore.getScore(), realScore.getSubject(), student.getLicenseType())) {
            studentService.lambdaUpdate()
                    .eq(Student::getId, studentId)
                    .set(Student::getStage, student.getStage() + 1)
                    .update();
        }

        save(realScore);
        return Result.success();
    }
}




